package cn.ihoway.redis;

import cn.ihoway.entity.Allocation;
import cn.ihoway.util.HowayLog;
import cn.ihoway.util.HowayRedisCache;

import java.util.ArrayList;
import java.util.List;

public class AllocationRedis {
    private HowayRedisCache cache = new HowayRedisCache(Allocation.class.getName());
    private final HowayLog logger = new HowayLog(AllocationRedis.class);
    //private final AllocationService allocationService = new AllocationServiceImpl();

    /**
     * 新增(使用update进行添加就行)
     */
    @Deprecated
    public void add(Allocation allocation){
        cache.putObject(getKey(allocation),allocation);
    }

    /**
     * 更新
     * @param allocation
     */
    public void update(Allocation allocation){
        //删除原有的(避免改变key导致原有的数据没有被删除)
        Allocation oldAllocation = getBySessionId(allocation.getSessionId());
        if(oldAllocation != null){
            cache.removeObject(getKey(oldAllocation));
        }
        cache.putObject(getKey(allocation),allocation);
    }

    /**
     * 按格式取出满足相应条件的全部数据集合,若不关心该条件是否满足则置为null
     * 条件顺序为key的顺序：roomId sessionId playerId isAlive isReady
     * @return list
     */
    public List<Allocation> getConditionMatch(Object... arguments){
        return cache.getConditionMatch(" ",arguments);
    }

    public void remove(Allocation allocation){
        cache.removeObject(getKey(allocation));
    }

    //key: roomId+sessionId+playerId+isAlive+isReady,其中sessionId是不变的，后面三个可能更改
    private String getKey(Allocation allocation){
        return allocation.getRoomId() + " " + allocation.getSessionId()
                + " " + allocation.getPlayerId() + " " + allocation.getIsAlive() + " " + allocation.getIsReady();
    }

    //获取某个房间内比指定序号大的玩家
    public List<Allocation> searchMore(String roomId,Integer playerId){
        List<Allocation> allocationList = getByRoomId(roomId);
        List<Allocation> resList = new ArrayList<>();
        for(Allocation allocation : allocationList){
            if(Integer.parseInt(allocation.getPlayerId()) > playerId){
                resList.add(allocation);
            }
        }
        return resList;
    }

    public Allocation getBySessionId(String sessionId){
        List<Allocation> allocationList = getConditionMatch(null,sessionId,null,null,null);
        if(allocationList.isEmpty()){
            return null;
        }
        return allocationList.get(0);
    }

    public List<Allocation> getByRoomId(String roomId){
        return getConditionMatch(roomId,null,null,null,null);
    }

    public List<Allocation> getReadyByRoomId(String roomId){
        return getConditionMatch(roomId,null,null,null,1);
    }

    public int getReadyNums(String roomId){
        return getReadyByRoomId(roomId).size();
    }


}
